package com.acxiom.foodreview.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import com.acxiom.foodreview.dao.SysUserDao;
import com.acxiom.foodreview.entity.SysRole;
import com.acxiom.foodreview.entity.SysUser;

@Component
public class SysUserDetailsService implements UserDetailsService {

	@Autowired
	private SysUserDao sysUserDao;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (StringUtils.isBlank(username)) {
			throw new UsernameNotFoundException("用户名不能为空");
		}
		SysUser sysUser = sysUserDao.findByUserName(username);
		if (null == sysUser) {
			throw new UsernameNotFoundException("用户不存在");
		}

		List<SimpleGrantedAuthority> authorities = new ArrayList<>();
		for (SysRole role : sysUser.getRoles()) {
			authorities.add(new SimpleGrantedAuthority(role.getName()));
		}
		sysUser.setGrantedAuthorities(authorities);
		return sysUser;
	}

}
